class Api::V1::DepositsController < Api::V1::BaseController
  skip_before_action :authenticate_request!, only: [:notify, :alipay_notify]

  def index
    @deposits = @current_user.deposits.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def create
    @deposit = Deposit.new deposit_params
    if @deposit.money <= 0
      render json: { result: false, message: '充值最低1元.' }, status: :ok and return
    end
    @deposit.user_id = @current_user.id
    @deposit.state = :pending
    @deposit.trade_no = "CZ" + Time.now.strftime('%Y%m%d%H%M%S') + rand(999).to_s
    if @deposit.save
      render json: { result: true, message: '充值成功.', data: { id: @deposit.id } }, status: :ok
    else
      render json: { result: false, message: '充值失败.' }, status: :ok
    end
  end

  def destroy
    @deposit = Deposit.find params[:id]
    if @deposit.pending? && @deposit.user_id == @current_user.id
      if @deposit.destroy
        render json: { result: true, message: '删除成功.' }, status: :ok
      else
        render json: { result: false, message: '删除失败.' }, status: :ok
      end
    else
      render json: { result: false, message: '该充值信息不能删除.' }, status: :ok
    end
  end

  def pay
    params[:pay_method] ||= 'wepay'
    deposit = Deposit.find_by_id params[:deposit_id]
    if deposit.blank? || deposit.user_id != @current_user.id
      render json: { result: false, message: '订单不存在.' }, status: :ok and return
    end
    if deposit.checkouted?
      render json: { result: false, message: '订单已支付.' }, status: :ok and return
    end
    trade_no = deposit.trade_no
    total_fee = deposit.money
    deposit.update_column("pay_method", params[:pay_method])

    if total_fee == 0
      render json: { result: false, message: '支付价格为0元，不能支付.' }, status: :ok and return
    end
    
    if params[:pay_method] == 'wepay'
      prepay_params = {
        body: "#{Setting.fetch("app_name")}充值",
        out_trade_no: trade_no,
        total_fee: (total_fee * 100).to_i,
        spbill_create_ip: request.remote_ip,
        notify_url: Figaro.env.wechat_deposits_notify_url,
        trade_type: 'APP'
      }
      prepay_result = WxPay::Service.invoke_unifiedorder prepay_params
      if prepay_result.success?
        pay_params = {
          prepayid: prepay_result['prepay_id'],
          noncestr: prepay_result['nonce_str']
        }
        pay_result = WxPay::Service.generate_app_pay_req pay_params
        render json: { result: true, message: '获取微信支付数据成功.', data: pay_result }, status: :ok
      else
        render json: { result: false, message: '申请微信订单失败.', data: prepay_result }, status: :ok
      end
    elsif params[:pay_method] == 'alipay'
      @client = Alipay::Client.new(
        url: Figaro.env.alipay_url,
        app_id: Figaro.env.alipay_app_id,
        app_private_key: Figaro.env.alipay_app_private_key,
        alipay_public_key: Figaro.env.alipay_public_key
      )
      pay_result = @client.sdk_execute(
        method: 'alipay.trade.app.pay',
        notify_url: Figaro.env.alipay_deposits_notify_url,
        biz_content: {
          out_trade_no: "#{trade_no}",
          product_code: 'QUICK_MSECURITY_PAY',
          total_amount: "#{total_fee}",
          subject: "#{Setting.fetch("app_name")}充值"
        }.to_json(ascii_only: true),
        timestamp: Time.now.strftime('%Y-%m-%d %H:%M:%S')
      )
      render json: { result: true, message: '获取支付宝支付数据成功.', data: pay_result }, status: :ok
    end
  end

  def notify
    result = Hash.from_xml(request.body.read)["xml"]
  
    if WxPay::Sign.verify?(result)
      deposit = Deposit.find_by_trade_no(result["out_trade_no"])
      deposit.update_attributes(state: :checkouted)
      bouns = 0.0
      DepositPreference.all.order("full_money DESC").each do |deposit_preference|
        if deposit_preference.published && deposit.money >= deposit_preference.full_money
          bouns = deposit_preference.bonus
          break
        end
      end
      deposit.user.update_attributes(moneybag: deposit.user.moneybag + deposit.money + bouns)
      deposit.send_notify("支付成功.", 'Native', 'topup_page')
      render :xml => {return_code: "SUCCESS"}.to_xml(root: 'xml', dasherize: false)
    else
      render :xml => {return_code: "FAIL", return_msg: "签名失败"}.to_xml(root: 'xml', dasherize: false)
    end
  end

  def alipay_notify
    @client = Alipay::Client.new(
      url: Figaro.env.alipay_url,
      app_id: Figaro.env.alipay_app_id,
      app_private_key: Figaro.env.alipay_app_private_key,
      alipay_public_key: Figaro.env.alipay_public_key
    )
    if @client.verify?(request.request_parameters)
      deposit = Deposit.find_by_trade_no(params[:out_trade_no])
      deposit.update_attributes(state: :checkouted)
      bouns = 0.0
      DepositPreference.all.order("full_money DESC").each do |deposit_preference|
        if deposit_preference.published && deposit.money >= deposit_preference.full_money
          bouns = deposit_preference.bonus
          break
        end
      end
      deposit.user.update_attributes(moneybag: deposit.user.moneybag + deposit.money + bouns)
      deposit.send_notify("支付成功.", 'Native', 'topup_page')
      render plain: 'success'
    end
  end

  private

  def deposit_params
    params.require(:deposit).permit(:money)
  end
  
end
